package com.cqie.hospitalescort.service.weixin;

import com.alibaba.fastjson.JSON;
import com.cqie.hospitalescort.DTO.WeiXinSessionInfoDTO;
import com.cqie.hospitalescort.exception.BusinessException;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

@Service
public class WeiXinServiceImpl implements WeiXinService {

    @Value("${jwt.app-i-d}")
    private String appid;

    @Value("${jwt.app-secret}")
    private String appSecret;

    @Autowired
    private RestTemplate restTemplate;

    private String accessToken = null;
    private long expiresTime = 0; // Access token 的过期时间戳

    /**
     * auth.code2Session
     *
     * @param code
     * @return
     */
    @Override
    public WeiXinSessionInfoDTO getSessionInfo(String code) {
        String url = String.format(WeiXinContacts.SESSION_INFO_URL, appid, appSecret, code);

        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, null, String.class);
        if (!response.getStatusCode().is2xxSuccessful()) {
            throw new BusinessException("调用微信接口[/sns/jscode2session]失败!");
        }
        return JSON.parseObject(response.getBody(), WeiXinSessionInfoDTO.class);
    }

    /**
     * 发送模板消息
     *
     * @param openId
     */
    @Override
    public void sendNotification(String openId) {
        String accessToken = getAccessToken(); // 实现获取access_token的方法
        String url = String.format(WeiXinContacts.SEND_TEMPLATE_MSG_URL, accessToken);

        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("touser", openId);
        requestBody.put("msgtype", "text");
        Map<String, String> text = new HashMap<>();
        text.put("content", "您的陪诊员权限已开通，请重新登录以获取最新权限。");
        requestBody.put("text", text);

        String s = restTemplate.postForObject(url, requestBody, String.class);
        System.out.println(s);
    }

    /**
     * 获取 access token
     * @return 返回 access token 字符串
     */
    public String getAccessToken() {
        // 如果当前token未过期，则直接返回
        if (accessToken != null && System.currentTimeMillis() < expiresTime) {
            return accessToken;
        }

        String url = String.format(WeiXinContacts.ACCESS_TOKEN_URL, appid, appSecret);

        ResponseEntity<AccessTokenResponse> responseEntity = restTemplate.getForEntity(url, AccessTokenResponse.class);

        if (responseEntity.getStatusCode().is2xxSuccessful()) {
            AccessTokenResponse body = responseEntity.getBody();
            if (body != null) {
                accessToken = body.getAccess_token();
                // 设置过期时间，提前5分钟刷新以防止过期
                expiresTime = System.currentTimeMillis() + (body.getExpires_in() - 300) * 1000L;
                return accessToken;
            }
        }

        throw new BusinessException("Failed to get access token");
    }


    @Data
    private static class AccessTokenResponse {
        private String access_token;
        private int expires_in;
    }
}
